package edu.task.service.impl;

import edu.task.common.constant.UserConstants;
import edu.task.common.result.TableDataInfo;
import edu.task.common.security.SecurityUtils;
import edu.task.mapper.Mapper;
import edu.task.model.SysUser;
import edu.task.model.SysUserRole;
import edu.task.model.vo.SysUserVO;
import edu.task.repository.SysUserRepository;
import edu.task.repository.SysUserRoleRepository;
import edu.task.service.SysUserService;
import edu.task.utils.BeanUtils;
import edu.task.utils.StringUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 用户表业务层
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    SysUserRepository sysUserRepository;

    @Autowired
    SysUserRoleRepository sysUserRoleRepository;

    @Autowired
    Mapper mapper;

    @Value("${spring.mail.username}")
    private String from;   // 邮件发送人

    @Autowired
    private JavaMailSender mailSender;


    @Override
    public TableDataInfo selectUserList(SysUserVO user, Pageable page) {
        SysUser sysuser = new SysUser();
        BeanUtils.copyPropertiesIgnoreEmpty(user, sysuser);
        sysuser.setDelFlag("0");
        // 通过使用 Spring Date JPA 的 ExampleMatcher 匹配器构建模糊查询条件
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("userName", ExampleMatcher.GenericPropertyMatchers.contains()) //"userName"字段模糊匹配
                .withMatcher("phonenumber", ExampleMatcher.GenericPropertyMatchers.contains()); //"phonenumber"字段模糊匹配
        Example<SysUser> example = Example.of(sysuser, exampleMatcher); //动态查询
        Page<SysUser> rs = sysUserRepository.findAll(example, page); //分页
        return TableDataInfo.success(rs.toList(), rs.getTotalElements());
    }

    @Override
    public String checkUserNameUnique(String userName) {
        SysUser sysuser = new SysUser();
        sysuser.setUserName(userName);
        return count(sysuser);
    }

    @Override
    public String checkPhoneUnique(SysUserVO userInfo) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userInfo, user);
        return checkUnique(user);
    }

    @Override
    public String checkEmailUnique(SysUserVO userInfo) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userInfo, user);
        return checkUnique(user);
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @Override
    @Transactional
    public boolean insertUser(SysUserVO user) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(user, sysUser);
        sysUser.setDelFlag("0");
        // 密码加密
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        Date date = new Date();
        sysUser.setCreateTime(date);
        sysUser.setUpdateTime(date);
        // 新增用户信息并且返回新增用户ID
        mapper.insertUser(sysUser);

//        sysUserRepository.save(sysUser);
        user.setUserId(sysUser.getUserId());

        //新增用户和角色管理
        insertUserRole(user);
        return null != sysUser.getUserId();
    }

    /**
     * 新增用户角色信息
     * @param user 用户对象
     */
    @Transactional
    public int insertUserRole(SysUserVO user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNull(roles) || roles.length == 0) {
            roles = new Long[]{Long.valueOf(6)};
        }
        Long[] userIds = new Long[roles.length];
        Long userId = user.getUserId();
        for (Long roleId : roles) {

            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            sysUserRoleRepository.save(sysUserRole);
        }
        Arrays.fill(userIds, user.getUserId());
        return 1;
    }

    @Override
    public String count(SysUser sysuser) {
        Example<SysUser> example = Example.of(sysuser);
        long count = sysUserRepository.count(example);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        Example<SysUser> example = Example.of(user);
        SysUser info = findOne(example);
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public SysUser findOne(Example<SysUser> example) {
        List<SysUser> list = sysUserRepository.findAll(example, PageRequest.of(0, 1)).toList();
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        return sysUserRepository.deleteUserByIds(userIds);
    }

    @Override
    @Transactional
    public boolean updateUser(SysUserVO user) {
        Long userId = user.getUserId();
        Optional<SysUser> op = sysUserRepository.findById(userId);
        //判断optional是否为空
        if (!op.isPresent()) {
            return false;
        }
        // 删除用户与角色关联
        sysUserRepository.deleteUserRoleByUserId(userId);
        // 返回该对象
        SysUser sysUser = op.get();
        BeanUtils.copyPropertiesIgnoreNull(user, sysUser);
        //更新用户信息
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        sysUserRepository.save(sysUser);
        //新增用户与角色关联
        insertUserRole(user);
        return null != sysUser.getUserId();
    }

    @Override
    public SysUser selectUserById(Long userId) {
        SysUser sysuser = new SysUser();
        sysuser.setUserId(userId);
        sysuser.setDelFlag("0");
        return sysUserRepository.findOne(Example.of(sysuser)).get();
    }

    @Override
    public List<SysUser> selectUserByName(String name) {
        return sysUserRepository.selectUserByName(name);
    }

    @SneakyThrows
    @Override
    public void sendMsg(String to, String subject, String context) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        String nick = MimeUtility.encodeText("任务系统");
        //邮件发送人
        mailMessage.setFrom(String.valueOf(new InternetAddress(nick+ "<"+ "2930742015@qq.com"+ ">")));
//        mailMessage.setFrom(from);
        //邮件接收人
        mailMessage.setTo(to);
        //邮件主题，也就是标题
        mailMessage.setSubject(subject);
        //邮件内容
        mailMessage.setText(context);

        // 真正的发送邮件操作，从 from到 to
        mailSender.send(mailMessage);
    }

    @Override
    public SysUser selectUserByUserName(String username) {
        SysUser user=new SysUser();
        user.setUserName(username);
        user.setDelFlag("0");
        Example<SysUser> example=Example.of(user);
        return findOne(example);
    }

    @Override
    public boolean updatePassword(SysUser sysUser) {
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        sysUserRepository.save(sysUser);
        return null != sysUser.getUserId();
    }
}
